<!--
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-07-30 20:02:30
 * @LastEditTime: 2020-02-28 11:25:38
 * @LastEditors: Please set LastEditors
 -->
<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport"
        content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <title></title>
    <link rel="stylesheet" type="text/css" href="../css/vant.css">
    <link rel="stylesheet" type="text/css" href="../css/base.css" />
    <script type="text/javascript" src="../script/vue.min.js"></script>
    <script type="text/javascript" src="../script/vant.min.js"></script>
    <script type="text/javascript" src="../script/base.js"></script>
    <script type="text/javascript" src="../script/jquery.js"></script>
    <script type="text/javascript" src="../script/ajaxFileUpload.js"></script>
    <script type="text/javascript" src="../script/layer/mobile/layer.js"></script>
    <style type="text/css">
        .content {
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }

        .mainForm {
            display: flex;
            flex-wrap: wrap;
            background-color: #fff;
        }

        .van-field {
            width: 50%;
            display: flex;
            align-items: center;
        }

        .van-cell {
            width: 50%;
        }

        .bottomBtn {
            height: 50px;
            width: 100%;
            padding: 10px 10px;
            display: flex;
        }

        .bottomBtn button {
            flex: 1;
            margin: 0 10px;
        }

        .wrapper {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            /* ✅ 填满视口，才能让 .block 充分使用空间 */
            overflow: hidden;
        }

        .block {
            width: 80vw;
            max-height: 90vh;
            background-color: #fff;
            overflow-y: auto;
            padding: 16px;
            box-sizing: border-box;
        }


        /* 新增滚动容器 */
        .content-scroll {
            flex: 1;
            overflow: auto;
            display: flex;
            flex-direction: column;
        }

        .table-container {
            max-height: 30vh;
            overflow: auto;
        }

        .table table {
            padding: 0;
            margin: 0;
            width: 100%;
            border-collapse: collapse;
            color: #fff;
            table-layout: fixed;
        }




        .table table tr th {
            /* text-align: center;
            color: #fff;
            height: 34px;
            white-space: nowrap;
            padding: 0 5px;
            border: 1px solid #808080;
            background-color: #4ba2f9;
            position: sticky;
            white-space: nowrap;
            overflow-x: scroll; */
            text-align: center;
            color: #fff;
            height: 34px;
            padding: 0 5px;
            border: 1px solid #808080;
            background-color: #4ba2f9;
            white-space: nowrap;
            position: static;

        }

        .table table tr td {
            text-align: center;
            height: 34px;
            white-space: nowrap;
            padding: 0 5px;
            border: 1px solid #808080;
            color: #000;
            position: relative;
            overflow-x: scroll;
        }




        .newlineDiv {
            white-space: normal;
            word-wrap: break-word;
            word-break: break-all;
        }

        .table table tr:active td {
            color: #000;
        }

        .search {
            position: fixed;
            bottom: 20vh;
            right: 3vw;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
            background: #4ba2f9;
            color: #fff;
        }



        .Detailsbutton {
            width: 100%;
            text-align: center;
        }

        /* .Detailsbutton button {
            margin: 1% 0;
            display: inline-block;
            color: #fff;
            background-color: #51d0d0;
            font-size: 20px;
        } */

        .Detailsbutton button {
            width: 40%;
        }

        .td_view {
            display: flex;
            align-items: center;
            border: none;
        }

        .SOPView {
            flex: 1;
            box-sizing: border-box;
        }

        .td_view>.SOPView>.van-icon {
            color: red;
        }
    </style>
</head>

<body>
    <div id="app" v-cloak>
        <div class="box">
            <van-nav-bar :title="name + '明细'" id="safeTop" left-arrow @click-left="onClickLeft">
                <!-- @click-right="openScan(1)"> -->
                <!-- <template #right>
                    <van-button v-if="!baseFormData.TraceID" size="small" type="default" color='#4ba2f9' icon="scan">
                    </van-button>

                </template> -->
            </van-nav-bar>
            <div class="content">
                <div class="mainForm">

                    <van-field v-model="baseFormData.BillDate" label="绑定日期:" placeholder="请选择日期" readonly
                        @click="handlerDate('绑定日期')"></van-field>

                    <van-field v-model="baseFormData.BillNO" label="单据编号：" readonly></van-field>
                    <van-field v-model="baseFormData.FWorkshopName" label="生产车间：" placeholder="自动带出生产车间" readonly>
                    </van-field>


                    <div class="table">
                        <table>
                            <tr>
                                <th width='20%'>工单编号</th>
                                <th width='21%'>派工单编号</th>
                                <th>产品编码</th>
                                <th>产品规格</th>
                                <th width='12%'>绑定状态</th>
                                <th width='10%' v-if="!baseFormData.TraceID">操作</th>
                            </tr>
                            <tr v-for="(item,index) in formData" :key="index" @click="clickpopup_show(item)">
                                <td>{{item.GDBillNO}}</td>
                                <td>{{item.PGDBillNO}}</td>
                                <td>{{item.ProductCode}}</td>
                                <td>{{item.ProductSpec}}</td>
                                <td :style="getBindStyleByID(item.BindStatus)">{{getBindNameByID(item.BindStatus)}}
                                </td>
                                <td v-if="!baseFormData.TraceID">
                                    <div>
                                        <van-button type="warning" @click="formData_del(index,item)">删除
                                        </van-button>
                                    </div>
                                </td>
                            </tr>
                        </table>

                    </div>
                    <div class="search" @click="openScan(1)" v-if="!baseFormData.TraceID" v-show="api.deviceModel != 'TC27'">
                        <van-icon name="scan" />
                    </div>
                </div>

                <div class="Detailsbutton">
                    <van-button type="info" v-if="!baseFormData.TraceID" @click="submit_Add">确定</van-button>

                    <van-button type="info" v-if="baseFormData.TraceID" @click="submit_Edit">修改</van-button>


                </div>
            </div>

            <van-popup v-model="dateShow" position="bottom">
                <van-datetime-picker v-model="currentDate" type="date" title="选择操作日期" @confirm="confirmDate"
                    @cancel="dateShow = false"></van-datetime-picker>
            </van-popup>

            <!-- <van-overlay :show="popup_show" @click="popup_show = false" :lock-scroll="false"> -->
            <van-overlay :show="popup_show" :lock-scroll="false">
                <div class="wrapper">
                    <div class="block">
                        <div class="mainForm">
                            <van-field v-model="batchFormData.PGDBillNO" label="派工单号:"></van-field>
                            <van-field v-model="batchFormData.ProductCode" label="产品编码:"></van-field>
                            <van-field v-model="batchFormData.ProductName" label="产品名称:"></van-field>
                            <van-field v-model="batchFormData.ProductSpec" label="产品规格:"></van-field>
                        </div>
                        <div class="table">
                            <table>
                                <tr>
                                    <th>物料编码</th>
                                    <th>物料名称</th>
                                    <th>物料规格</th>
                                    <th>批次号</th>
                                    <th width='10%'>操作</th>
                                </tr>
                                <tr v-for=" (batchItem, index) in batchList">

                                    <td>{{batchItem.ProductCode}}</td>
                                    <td>{{batchItem.ProductName}}</td>
                                    <td>{{batchItem.ProductSpec}}</td>

                                    <td>
                                        <div class="td_view">
                                            <div class="ListTdDiv"><span>{{batchItem.FBatchNo}}</span></div>
                                            <div class="SOPView" v-if="batchItem.FBatchNo"
                                                @click="clearFBatchNo(index)">
                                                <van-icon name="delete" size='20px'></van-icon>

                                            </div>
                                        </div>

                                    </td>

                                    <td>
                                        <div @click.stop>
                                            <van-button type="warning" size="small" @click.stop
                                                @click="batchList_del(index,batchItem)">删除</van-button>
                                        </div>
                                    </td>
                                </tr>
                            </table>

                        </div>
                        <div class="search" @click="openScan(2)" style="z-index: 1;" v-show="api.deviceModel != 'TC27'">
                            <van-icon name="scan" />
                        </div>
                        <div class="Detailsbutton">
                            <van-button type="info" @click="submit_batch">确定</van-button>

                        </div>


                    </div>
                </div>
            </van-overlay>

            <audio id="audioPlayer" preload="auto">
                <source src="../image/aigei_com.mp3" type="audio/mpeg">
            </audio>
            <div class="indexBottom">
                汇智云创 技术支持
            </div>
        </div>
    </div>

</body>

<script type="text/javascript">
    var vm;
    apiready = function () {
        var photoBrowser = api.require('photoBrowser');
        var scanTC27 = api.require('scanTC27');
        var FNScanner = api.require('FNScanner');

        api.addEventListener({
            name: 'getCDAlarmLList'
        }, function (ret) {
            APP.getCDAlarmLList()
        })

        api.addEventListener({
            name: 'getYCKBDataLiist'
        }, function (ret) {
            APP.getYCKBDataLiist()
        })
        api.addEventListener({
            name: 'selectRow'
        }, function (ret, err) {
            console.log('ret', JSON.stringify(ret))
            if (ret.value.type == '产品') {
                vm.formData.ProductID = ret.value.row.ProductID
                vm.formData.ProductSpec = ret.value.row.name
            }
            else if (ret.value.type == '型号') {
                vm.formData.ProductID = ret.value.row.ProductID
                vm.formData.ProductSpec = ret.value.row.ProductSpec
            }
        })
        vm = new Vue({
            el: '#app',
            data: {
                tableData: [],
                popup_show: false,
                currentDateVal: '',
                dateShow: false,
                currentDate: new Date(),
                formData: [],
                baseFormData: {
                    TraceID: 0,
                    BillDate: '',
                    BillNO: '自动生成',
                    // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1!
                    FWorkshopID: 1027,
                    FWorkshopName: '充电车间',
                    // FWorkshopID: 1009
                    // FWorkshopID: 1009,
                    // FWorkshopName: '装配车间',
                },
                LimitBind: 0,
                batchList: [],
                batchFormData: {
                    PGDBillNO: '',
                    ProductCode: '',
                    ProductSpec: '',
                },
                name: api.pageParam.name,
                tableData: [],
            },
            created: function () {
                var that = this;
                window.localStorage.setItem('pageName', JSON.stringify(that.name))
                console.log(JSON.stringify(api.pageParam.TraceID));

                if (api.pageParam.TraceID) {
                    this.baseFormData.TraceID = api.pageParam.TraceID;
                    this.getDetail();
                } else {
                    this.baseFormData.BillDate = APP.getFormatbeforDate()
                }
                scanTC27.registerReceiver(function (ret, err) {
                    console.log('scanTC27 扫码结果：' + JSON.stringify(ret));
                    if (ret && ret.barcode) {
                        // 调用统一分发函数（注意这里的 that 需提前绑定正确的上下文）
                        that.dispatchScanResult(ret.barcode, that);
                    } else {
                        api.toast({ msg: '扫描失败' });
                    }
                });


            },
            mounted() {
                var that = this

                APP.setSafeTop()
                APP.keyBoardChange()
                let obj = {
                    FWorkshopID: that.baseFormData.FWorkshopID
                }
                APP.ajax('getLimitBind', obj, function (res) {
                    console.log(JSON.stringify(res));
                    that.LimitBind = res.ds[0].LimitBind
                    console.log(that.LimitBind)

                }, function (err) {
                    console.log(JSON.stringify(err))
                })
                // that.popup_show = true
            },

            methods: {

                handlerDate(str) {
                    var that = this
                    that.dateShow = true
                    that.currentDateVal = str
                },
                confirmDate() {
                    var that = this
                    if (that.currentDateVal == '绑定日期') {
                        that.baseFormData.BillDate = APP.getFormatDate(that.currentDate).split(' ')[0]

                    }
                    that.dateShow = false
                },
                getBindStyleByID(id) {
                    let obj = {

                    }
                    switch (id) {
                        case 0:
                            obj = {
                                color: 'red'
                            }
                            break;
                        case 1:
                            obj = {
                                color: 'red'
                            }
                            break;
                        case 2:
                            obj = {
                                color: 'green'
                            }
                            break;
                        default:
                            obj = {}
                    }

                    return obj
                },
                getBindNameByID(id) {
                    let name = ''
                    switch (id) {
                        case 0:
                            name = '未绑定'
                            break;
                        case 1:
                            name = '部分绑定'
                            break;
                        case 2:
                            name = '全部绑定'
                            break;
                        default:
                            name = ''
                    }

                    return name
                },
                getBindStatus(item) {
                    let that = this;

                    let BindStatus = 0;

                    try {
                        if (item.batchList.every((ele) => {
                            return ele.FBatchNo
                        })) {
                            BindStatus = 2;
                        } else if (item.batchList.every((ele) => {
                            return !ele.FBatchNo
                        })) {
                            BindStatus = 0;
                        } else if (item.batchList.some((ele) => {
                            return !ele.FBatchNo
                        })) {
                            BindStatus = 1;
                        }
                    } catch (e) {
                        console.log(e);
                        BindStatus = 0;
                    }


                    return BindStatus

                },

                TakeBindStatus() {
                    let that = this;
                    that.formData.forEach((data) => {
                        // console.log(data);
                        data.BindStatus = that.getBindStatus(data)
                    })
                },

                getDetail() {
                    let that = this;
                    let obj = {
                        TraceID: that.baseFormData.TraceID
                    }
                    console.log(JSON.stringify(obj));
                    APP.ajax('batchTraceDetail', obj, function (res) {
                        console.log(JSON.stringify(res));
                        that.baseFormData.BillDate = res.ds[0].BillDate;
                        that.baseFormData.BillNO = res.ds[0].BillNO;
                        that.baseFormData.FWorkshopID = res.ds[0].FWorkshopID;
                        that.baseFormData.FWorkshopName = res.ds[0].FWorkshopName;
                        let tmp = []

                        res.ds.forEach((item) => {
                            let obj = {
                                TraceID: item.TraceID,
                                JobOrderID: item.JobOrderID,
                                PGDBillNO: item.PGDBillNO,
                                WoOrderID: item.WoOrderID,
                                GDBillNO: item.GDBillNO,
                                ProductID: item.ProductID,
                                ProductCode: item.ProductCode,
                                ProductName: item.ProductName,
                                ProductSpec: item.ProductSpec,
                                BindStatus: item.BindStatus,
                            }

                            obj.batchList = that.getBatchList((res.ds1 || []), item)

                            tmp.push(obj)
                        })
                        that.formData = tmp;
                        Promise.resolve().then(() => {
                            that.clickpopup_show(that.formData[0]);
                        })



                    }, function (err) {
                        console.log(JSON.stringify(err))
                    })
                },
                getBatchList(arr, item) {
                    let batchList = []
                    batchList = arr.filter((ele) => {
                        return ele.TraceID == item.TraceID;
                    })
                    return batchList

                },
                formData_del(index, item) {
                    var that = this;
                    let content = '是否删除此条数据？'
                    if (item.BindStatus == 2) {
                        content = '该条派工单数据已全部绑定批次，是否删除此条数据？'
                    }
                    api.confirm({
                        title: '提示',
                        msg: content,
                        buttons: ['确认', '取消']
                    }, function (ret, err) {
                        if (ret.buttonIndex == 1) {
                            that.formData.splice(index, 1);
                        }
                    });

                },
                batchList_del(index, item) {
                    var that = this;



                    api.confirm({
                        title: '提示',
                        msg: '是否删除此条数据？',
                        buttons: ['确认', '取消']
                    }, function (ret, err) {
                        if (ret.buttonIndex == 1) {
                            let matchList = [];
                            matchList = that.batchList.filter((ele) => {
                                return ele.ProductID == item.ProductID
                            })
                            if (matchList.length == 1) {
                                api.toast({
                                    msg: '请至少保留一行该物料！！'
                                })
                            } else {
                                that.batchList.splice(index, 1);
                            }
                        }
                    });


                },
                openScan(str) {
                    var that = this
                    var resultList = api.hasPermission({
                        list: ['camera']
                    });
                    if (resultList[0].granted) {
                        // 已授权，可以继续下一步操作
                        that.openFNScanner()

                    } else {
                        api.confirm({
                            msg: '应用需要您的授权才能访问相机',
                            buttons: ['取消', '去设置']
                        }, function (ret) {
                            if (ret.buttonIndex == 2) {
                                api.requestPermission({
                                    list: ['camera'],
                                }, function (res) {
                                    if (res.list[0].granted) {
                                        that.openFNScanner()

                                    }
                                });
                            }
                        });
                    }
                },

                // 1. 改造 FNScanner.open 调用（以 openFNScanner1 为例，openFNScanner2 类似）
                openFNScanner() {
                    let that = this;
                    console.log('openFNScanner');
                    FNScanner.open({ autorotation: true }, function (ret, err) {
                        console.log('FNScanner 扫码结果：', JSON.stringify(ret));
                        if (ret && ret.content) {
                            // 直接调用统一分发函数
                            that.dispatchScanResult(ret.content, that);
                        }
                        // else {
                        //     api.toast({ msg: '扫描失败' });
                        // }
                    });


                },


                // openFNScanner1() {
                //     let that = this;
                //     console.log('openFNScanner1');
                //     FNScanner.open({
                //         autorotation: true
                //     }, function (ret, err) {
                //         console.log(JSON.stringify(ret));

                //         if (ret) {
                //             if (ret.content) {
                //                 let IsPGD = false;
                //                 try {
                //                     IsPGD = (ret.content.split('|')[0] == 'PGD')
                //                 } catch (e) {
                //                     IsPGD = false;
                //                 }
                //                 if (IsPGD) {
                //                     let obj = {
                //                         JobOrderID: ret.content.split('|')[1],
                //                         FWorkshopID: that.baseFormData.FWorkshopID
                //                     }
                //                     APP.ajax('batchTraceScan', obj, function (res) {

                //                         if (res.ds[0].status && res.ds[0].status == 500) {
                //                             api.toast({
                //                                 msg: res.ds[0].msg
                //                             })

                //                         }
                //                         else {
                //                             let isExists = that.formData.some((item) => {
                //                                 return item.JobOrderID == res.ds[0].JobOrderID
                //                             })
                //                             if (isExists) {
                //                                 api.toast({
                //                                     msg: '当前扫描的派工单已存在！！'
                //                                 })
                //                             } else {
                //                                 let SearchBatchList = that.formData.filter((item) => {
                //                                     return item.ProductID == res.ds[0]
                //                                         .ProductID
                //                                     //&& item.WoOrderID == res.ds[0].WoOrderID
                //                                 })

                //                                 if (SearchBatchList.length) {
                //                                     res.ds[0].batchList = SearchBatchList[0]
                //                                         .batchList || []
                //                                 } else {
                //                                     res.ds[0].batchList = res.ds1 || []
                //                                 }

                //                                 that.formData.push(res.ds[0])

                //                                 that.formData.sort((a, b) => {
                //                                     return a.ProductID - b.ProductID
                //                                 })

                //                                 that.TakeBindStatus()
                //                             }


                //                         }

                //                     }, function (err) {
                //                         console.log(JSON.stringify(err))
                //                     })

                //                 } else {
                //                     api.toast({
                //                         msg: '请扫描派工单二维码'
                //                     })
                //                 }

                //             }
                //         } else {
                //             api.toast({
                //                 msg: '扫描失败'
                //             })
                //         }
                //     });



                // },
                // openFNScanner2() {
                //     let that = this;
                //     console.log(222);

                //     FNScanner.open({
                //         autorotation: true
                //     }, function (ret, err) {
                //         console.log(JSON.stringify(ret));

                //         if (ret) {
                //             if (ret.content) {
                //                 let IsPCM = false;
                //                 try {
                //                     IsPCM = (ret.content.split('|')[0] == 'CPPCM')
                //                 } catch (e) {
                //                     IsPCM = false;
                //                 }

                //                 if (IsPCM) {
                //                     let obj = {
                //                         code: ret.content.split('|')[1],
                //                         batch: ret.content.split('|')[2],
                //                         JobOrderID: that.batchFormData.JobOrderID,
                //                     }
                //                     console.log(obj)
                //                     APP.ajax('batchTraceScan_PCM', obj, function (res) {

                //                         if (res.ds[0].status && res.ds[0].status == 500) {
                //                             api.toast({
                //                                 msg: res.ds[0].msg
                //                             })
                //                         }
                //                         else {
                //                             let isExists_Product = that.batchList.some((item) => {
                //                                 return item.ProductID == res.ds[0]
                //                                     .ProductID
                //                             })
                //                             if (!isExists_Product) {
                //                                 api.toast({
                //                                     msg: '请扫描与当前领料明细物料一致的物料批次码！！！'
                //                                 })
                //                             } else {
                //                                 let isExists_Product_FBatchNo = that.batchList.some((
                //                                     item) => {
                //                                     return item.ProductID == res.ds[0]
                //                                         .ProductID &&
                //                                         item.FBatchNo == res.ds[0].FBatchNo
                //                                 })
                //                                 if (isExists_Product_FBatchNo) {
                //                                     api.toast({
                //                                         msg: '当前扫描的物料批次码已存在！！'
                //                                     })
                //                                 } else {
                //                                     let matchList = [];
                //                                     matchList = that.batchList.filter((ele) => {
                //                                         return ele.ProductID == res.ds[0]
                //                                             .ProductID && !
                //                                             ele.FBatchNo
                //                                     })
                //                                     if (matchList.length == 1) {
                //                                         that.batchList.find((ele) => {
                //                                             return ele.ProductID == res.ds[0]
                //                                                 .ProductID && !
                //                                                 ele.FBatchNo
                //                                         }).FBatchNo = res.ds[0].FBatchNo;
                //                                     } else {
                //                                         that.batchList.push(res.ds[0])
                //                                         that.batchList.sort((a, b) => {
                //                                             return a.ProductID - b.ProductID
                //                                         })
                //                                     }
                //                                 }
                //                             }



                //                         }

                //                     }, function (err) {
                //                         console.log(JSON.stringify(err))
                //                     })

                //                 } else {
                //                     api.toast({
                //                         msg: '请扫描派工单二维码'
                //                     })
                //                 }

                //             }
                //         } else {
                //             api.toast({
                //                 msg: '扫描失败'
                //             })
                //         }
                //     });


                // },



                // 处理 PGD 类型扫码结果（对应 openFNScanner1 的逻辑）
                handlePGDResult(barcode, that) {
                    let JobOrderID = barcode.split('|')[1];
                    let obj = {
                        JobOrderID: JobOrderID,
                        FWorkshopID: that.baseFormData.FWorkshopID
                    };
                    APP.ajax('batchTraceScan', obj, function (res) {
                        if (res.ds[0].status && res.ds[0].status === 500) {
                            api.toast({ msg: res.ds[0].msg });
                            return;
                        }
                        // 检查是否已存在
                        let isExists = that.formData.some(item => item.JobOrderID === res.ds[0].JobOrderID);
                        if (isExists) {
                            api.toast({ msg: '当前扫描的派工单已存在！！' });
                            return;
                        }
                        // 处理批次列表
                        let SearchBatchList = that.formData.filter(item => item.ProductID === res.ds[0].ProductID);
                        res.ds[0].batchList = SearchBatchList.length ? SearchBatchList[0].batchList || [] : res.ds1 || [];
                        // 更新列表并排序
                        that.formData.push(res.ds[0]);
                        that.formData.sort((a, b) => a.ProductID - b.ProductID);
                        that.TakeBindStatus();
                    }, function (err) {
                        console.log('PGD 扫码接口错误：', JSON.stringify(err));
                    });
                },

                // 处理 CPPCM 类型扫码结果（对应 openFNScanner2 的逻辑）
                handleCPPCMResult(barcode, that) {
                    let [, code, batch] = barcode.split('|'); // 解构获取 code 和 batch
                    let obj = {
                        code: code,
                        batch: batch,
                        JobOrderID: that.batchFormData.JobOrderID,
                    };
                    APP.ajax('batchTraceScan_PCM', obj, function (res) {
                        if (res.ds[0].status && res.ds[0].status === 500) {
                            api.toast({ msg: res.ds[0].msg });
                            return;
                        }
                        // 检查物料是否匹配
                        let isExistsProduct = that.batchList.some(item => item.ProductID === res.ds[0].ProductID);
                        if (!isExistsProduct) {
                            api.toast({ msg: '请扫描与当前领料明细物料一致的物料批次码！！！' });
                            return;
                        }
                        // 检查批次是否已存在
                        let isExistsBatch = that.batchList.some(item =>
                            item.ProductID === res.ds[0].ProductID && item.FBatchNo === res.ds[0].FBatchNo
                        );
                        if (isExistsBatch) {
                            api.toast({ msg: '当前扫描的物料批次码已存在！！' });
                            return;
                        }
                        // 更新批次列表
                        let matchList = that.batchList.filter(ele => ele.ProductID === res.ds[0].ProductID && !ele.FBatchNo);
                        if (matchList.length === 1) {
                            matchList[0].FBatchNo = res.ds[0].FBatchNo;
                        } else {
                            that.batchList.push(res.ds[0]);
                            that.batchList.sort((a, b) => a.ProductID - b.ProductID);
                        }
                    }, function (err) {
                        console.log('CPPCM 扫码接口错误：', JSON.stringify(err));
                    });
                },

                // 统一扫码结果分发（判断类型并调用对应处理函数）
                dispatchScanResult(barcode, that) {
                    try {
                        const [prefix] = barcode.split('|'); // 获取前缀
                        if (prefix === 'PGD') {
                            that.handlePGDResult(barcode, that);
                        } else if (prefix === 'CPPCM') {
                            that.handleCPPCMResult(barcode, that);
                        } else {
                            api.toast({ msg: '请扫描正确的二维码（PGD 或 CPPCM 前缀）' });
                        }
                    } catch (e) {
                        api.toast({ msg: '扫码内容格式错误' });
                        console.error('扫码解析错误：', e);
                    }
                },


                clearFBatchNo(index) {
                    var that = this;

                    api.confirm({
                        title: '提示',
                        msg: '是否清除该批次？',
                        buttons: ['确认', '取消']
                    }, function (ret, err) {
                        if (ret.buttonIndex == 1) {
                            that.batchList[index].FBatchNo = '';

                        }
                    });



                },
                clickpopup_show(item) {
                    var that = this;
                    that.batchFormData = JSON.parse(JSON.stringify(item));

                    that.batchList = item.batchList || [];
                    that.popup_show = true;
                    this.$forceUpdate()
                },
                submit_Add() {
                    var that = this;
                    api.confirm({
                        title: '提示',
                        msg: '是否提交?',
                        buttons: ['确认', '取消']
                    }, function (ret, err) {
                        if (ret.buttonIndex == 1) {

                            if (!that.formData.length) {
                                api.toast({
                                    msg: '派工单列表不能为空！！'
                                })
                                return
                            }
                            if (that.formData.some((item) => {
                                return item.BindStatus != 2;
                            })) {
                                if (that.LimitBind == 1) {
                                    api.toast({
                                        msg: '存在未全部绑定批次的派工单！！'
                                    })
                                    return
                                }

                            }
                            let FBatchNos = [],
                                ProductIDs = [],
                                FQtys = [],
                                JobOrderIDs = [],
                                BindStatuss = []
                            that.formData.forEach((item) => {
                                if (item.batchList && item.batchList.length) {
                                    item.batchList.forEach((ele) => {
                                        FBatchNos.push(ele.FBatchNo);
                                        ProductIDs.push(ele.ProductID);
                                        FQtys.push(ele.FQty);
                                        JobOrderIDs.push(item.JobOrderID);
                                        BindStatuss.push(item.BindStatus);
                                    })
                                } else {
                                    FBatchNos.push('');
                                    ProductIDs.push('');
                                    FQtys.push('');
                                    JobOrderIDs.push(item.JobOrderID);
                                    BindStatuss.push(item.BindStatus);
                                }
                            })


                            let obj = {
                                BillDate: that.baseFormData.BillDate,
                                FWorkshopID: that.baseFormData.FWorkshopID,
                                FBatchNos: FBatchNos.join('~'),
                                ProductIDs: ProductIDs.join('~'),
                                FQtys: FQtys.join('~'),
                                JobOrderIDs: JobOrderIDs.join('~'),
                                BindStatuss: BindStatuss.join('~'),
                            }
                            console.log(obj)

                            APP.ajax('batchTraceSubmit', obj, function (res) {

                                if (res.ds[0].status && res.ds[0].status == 500) {
                                    api.toast({
                                        msg: res.ds[0].msg
                                    })
                                } else {
                                    api.toast({
                                        msg: res.ds[0].msg
                                    })

                                    setTimeout(function () {
                                        that.onClickLeft();
                                    }, 300)

                                }

                            }, function (err) {
                                console.log(JSON.stringify(err))
                            })



                        }
                        else {
                            // that.checkUpdate()
                        }



                    });






                },
                submit_Edit() {
                    var that = this;
                    api.confirm({
                        title: '提示',
                        msg: '是否提交修改？',
                        buttons: ['确认', '取消']
                    }, function (ret, err) {
                        if (ret.buttonIndex == 1) {
                            if (!that.formData.length) {
                                api.toast({
                                    msg: '派工单列表不能为空！！'
                                })
                                return
                            }
                            if (that.formData.some((item) => {
                                return item.BindStatus != 2;
                            })) {
                                if (that.LimitBind == 1) {
                                    api.toast({
                                        msg: '存在未全部绑定批次的派工单！！'
                                    })
                                    return
                                }
                            }
                            let FBatchNos = [],
                                ProductIDs = [],
                                FQtys = [],
                                JobOrderIDs = [],
                                TraceIDs = [],
                                BindStatuss = []
                            that.formData.forEach((item) => {
                                if (item.batchList && item.batchList.length) {
                                    item.batchList.forEach((ele) => {
                                        FBatchNos.push(ele.FBatchNo);
                                        ProductIDs.push(ele.ProductID);
                                        FQtys.push(ele.FQty);
                                        JobOrderIDs.push(item.JobOrderID);
                                        TraceIDs.push(item.TraceID);
                                        BindStatuss.push(item.BindStatus);
                                    })
                                } else {
                                    FBatchNos.push('');
                                    ProductIDs.push('');
                                    FQtys.push('');
                                    JobOrderIDs.push(item.JobOrderID);
                                    TraceIDs.push(item.TraceID);
                                    BindStatuss.push(item.BindStatus);
                                }
                            })

                            let obj = {
                                // TraceID: that.baseFormData.TraceID,
                                BillDate: that.baseFormData.BillDate,
                                FWorkshopID: that.baseFormData.FWorkshopID,
                                FBatchNos: FBatchNos.join('~'),
                                ProductIDs: ProductIDs.join('~'),
                                FQtys: FQtys.join('~'),
                                JobOrderIDs: JobOrderIDs.join('~'),
                                TraceIDs: TraceIDs.join('~'),
                                BindStatuss: BindStatuss.join('~'),
                            }
                            console.log(JSON.stringify(obj))

                            APP.ajax('batchTraceSubmit_Edit', obj, function (res) {
                                console.log(JSON.stringify(res))
                                if (res.ds[0].status && res.ds[0].status == 500) {
                                    api.toast({
                                        msg: res.ds[0].msg
                                    })
                                } else {
                                    api.toast({
                                        msg: res.ds[0].msg
                                    })
                                    that.getDetail();

                                }

                            }, function (err) {
                                console.log(JSON.stringify(err))
                            })


                        }
                        else {
                            // that.checkUpdate()
                        }



                    });

                },

                submit_batch() {
                    var that = this;
                    that.formData.forEach((item) => {
                        if (item.ProductID == that.batchFormData.ProductID
                            //&& item.WoOrderID == that.batchFormData.WoOrderID
                        ) {
                            item.batchList = that.batchList;
                        }
                    })
                    that.TakeBindStatus()
                    console.log(that.formData)
                    that.popup_show = false;
                },


                onClickLeft() {
                    var that = this
                    api.sendEvent({
                        name: 'refreshbatchTraceList'
                    })
                    api.closeWin()
                },
            }
        })
    };
</script>

</html>